package compress;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import java.io.ByteArrayOutputStream;

public class DeflateDemo {

    public static String unCompress(String compressStr) throws DataFormatException {
        byte[] decode = Base64.getUrlDecoder().decode(compressStr);

        Inflater inflater = new Inflater();
        inflater.setInput(decode);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(decode.length);
        byte[] buffer = new byte[1024];

        while (!inflater.finished()) {
            int count = inflater.inflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        inflater.end();
        return outputStream.toString();
    }

    public static String compress(String str)  {
        Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        deflater.setInput(bytes);
        deflater.finish();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bytes.length);
        byte[] buffer = new byte[1024];
        while (!deflater.finished()) {
            int count = deflater.deflate(buffer);
            outputStream.write(buffer, 0, count);
        }
        deflater.end();
        return Base64.getUrlEncoder().encodeToString(outputStream.toByteArray());
    }
}
